from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from .base import Base, TimestampMixin

class UserApiKey(Base, TimestampMixin):
    """
    用户API密钥模型
    用于存储用户的key、secret、第三方userid和内部user_id
    """
    __tablename__ = "user_api_keys"
    
    id = Column(Integer, primary_key=True, index=True)
    api_key = Column(String(100), unique=True, index=True, nullable=False, comment="API密钥")
    api_secret = Column(String(255), nullable=False, comment="API密钥秘钥")
    external_user_id = Column(String(100), index=True, nullable=True, comment="第三方用户ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="内部用户ID")
    exchange = Column(String(50), nullable=False, comment="交易所名称")
    
    # 关系
    user = relationship("User", backref="api_keys")
    
    def __repr__(self):
        return f"<UserApiKey {self.api_key}>"
    
    def get_api_key(self):
        """获取API密钥"""
        return self.api_key
    
    def get_api_secret(self):
        """获取API密钥秘钥"""
        return self.api_secret
    
    def get_credentials(self):
        """获取API凭证(key和secret)"""
        return {
            "api_key": self.api_key,
            "api_secret": self.api_secret,
            "exchange": self.exchange
        } 